let VSHADER_SOURCE =
    'attribute vec4 a_Position;\n' +
    'attribute vec4 a_Color;\n' +
    'varying vec4 v_Color;\n' +
    'void main() {\n' +
    ' gl_Position = a_Position;\n' +
    ' gl_PointSize = 10.0;\n' +
    ' v_Color = a_Color;\n' +   //将数据传给片元着色器
    '}\n';

let FSHADER_SOURCE =
    'precision mediump float;\n' +
    'varying vec4 v_Color;\n' +
    'void main() {\n' +
    ' gl_FragColor = v_Color;\n' +  //从顶点着色器接收数据
    '}\n';

function main() {
    let canvas = document.getElementById('webgl');

    let gl = getWebGLContext(canvas);
    if (!gl) {
        console.log('Failed to get the rendering context for WebGL');
        return;
    }

    if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
        console.log('Failed to initialize shaders');
        return;
    }

    let n = initVertexBuffers(gl);
    if (n < 0) {
        console.log('Failed to set the positions of the vertices');
        return;
    }

    gl.clearColor(0.0, 0.0, 0.0, 1.0);
    gl.clear(gl.COLOR_BUFFER_BIT);
    gl.drawArrays(gl.TRIANGLES, 0, n);
}

function initVertexBuffers(gl) {
    let verticesSizes = new Float32Array([
        //顶点坐标和颜色
        0.0, 0.5, 1.0, 0.0, 0.0,
        -0.5, -0.5, 0.0, 1.0, 0.0,
        0.5, -0.5, 0.0, 0.0, 1.0,
    ]);
    let n = 3;

    let vertexColorBuffer = gl.createBuffer();
    if (!vertexColorBuffer) {
        console.log('Failed to create the buffer object');
        return -1;
    }
    gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, verticesSizes, gl.STATIC_DRAW);

    let fSize = verticesSizes.BYTES_PER_ELEMENT;
    let a_Position = getAttribLocation(gl, 'a_Position');
    if (a_Position < 0) { return; }
    gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, fSize * 5, 0);
    gl.enableVertexAttribArray(a_Position);

    let a_Color = getAttribLocation(gl, 'a_Color');
    if (a_Color < 0) { return; }
    gl.vertexAttribPointer(a_Color, 3, gl.FLOAT, false, fSize * 5, fSize * 2);
    gl.enableVertexAttribArray(a_Color);

    return n;
}

function getAttribLocation(gl, name) {
    let p = gl.getAttribLocation(gl.program, name);
    if (p < 0) {
        console.error('Failed to get the storage location of', name);
    }
    return p;
}

function getUniformLocation(gl, name) {
    let p = gl.getUniformLocation(gl.program, name);
    if (p == 0) {
        console.error('Failed to get the storage location of', name);
    }
    return p;
}